
package com.kugou.game.sdk.ui.activity;

import com.kugou.download.DownloadFile;
import com.kugou.download.FileDownloader;
import com.kugou.download.IProgressListener;
import com.kugou.download.manager.ParamsWrapper;
import com.kugou.framework.base.LogUtil;
import com.kugou.game.sdk.api.common.ActivityOrientation;
import com.kugou.game.sdk.base.BaseSDKWorkerFragmentActivity;
import com.kugou.game.sdk.core.FolderManager;
import com.kugou.game.sdk.core.SDKControler;
import com.kugou.game.sdk.download.DownloadOperator;
import com.kugou.game.sdk.download.DownloadServiceUtil;
import com.kugou.game.sdk.entity.AppInfo;
import com.kugou.game.sdk.entity.ForceUpdateInfo;
import com.kugou.game.sdk.statistics.StatCmd;
import com.kugou.game.sdk.statistics.StaticsManager;
import com.kugou.game.sdk.utils.AppUtil;
import com.kugou.game.sdk.utils.AsyncImageLoader;
import com.kugou.game.sdk.utils.AsyncImageLoader.ImageCallback;
import com.kugou.game.sdk.utils.DownloadHelper;
import com.kugou.game.sdk.utils.FileUtil;
import com.kugou.game.sdk.utils.MD5Util;
import com.kugou.game.sdk.utils.Rx;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

/**
 * 描述:强制更新界面
 * 
 * @author ljc
 * @since 2015-1-19 下午2:02:40
 */
public class ForceUpdateActivity extends BaseSDKWorkerFragmentActivity implements
        View.OnClickListener, ImageCallback {

    private final String TAG = getClass().getSimpleName();

    private Context context;

    private View layoutUpdateContent, layoutDownloading, layoutRootView;

    private TextView tvUpdateContent, tvUpdateNow, tvAppName, tvDownloadedNum, tvDownloadSpeed,
            tvDownloadPercent, tvDownloadLeftTime;

    private ImageView ivBanner;

    private ProgressBar progressBar;

    private ForceUpdateInfo checkUpdateInfo;

    protected AsyncImageLoader mAsyncImageLoader;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setBackgroundDrawableResource(Rx.color.kg_common_translucence_lighter);

        context = this;
        setContentView(Rx.layout.kg_activity_force_update);
        checkUpdateInfo = getIntent().getParcelableExtra("checkUpdateInfo");
        initView();
        mAsyncImageLoader = new AsyncImageLoader();
        DownloadServiceUtil.addListener(mProgressListener);
        initAppIcon();
        initViewState();
    }

    private void initView() {
        layoutDownloading = findViewById(Rx.id.kg_layout_downloading);
        layoutUpdateContent = findViewById(Rx.id.kg_layout_update_content);
        layoutRootView = findViewById(Rx.id.kg_layout_rootview);
        // 设置宽高
        int[] screenSize = AppUtil.getScreenSize(this);
        int height = ViewGroup.LayoutParams.WRAP_CONTENT;
        int width = 0;
        if (SDKControler.getActivityOrientation() == ActivityOrientation.LANDSCAPE) {
            width = screenSize[0] * 1 / 2;
        } else {
            width = screenSize[0] * 8 / 10;
        }
        ViewGroup.LayoutParams params = layoutRootView.getLayoutParams();
        params.height = height;
        params.width = width;
        layoutRootView.setLayoutParams(params);
        ivBanner = (ImageView) findViewById(Rx.id.kg_iv_banner);
        ivBanner.setOnClickListener(this);
        ViewGroup.LayoutParams params1 = ivBanner.getLayoutParams();
        params1.width = width - AppUtil.dip2px(this, 10);
        params1.height = params1.width * 16 / 52;
        ivBanner.setLayoutParams(params1);

        tvUpdateContent = (TextView) findViewById(Rx.id.kg_tv_update_content);
        tvUpdateNow = (TextView) findViewById(Rx.id.kg_tv_update_now);
        tvUpdateNow.setText("立即更新");
        tvAppName = (TextView) findViewById(Rx.id.kg_tv_app_name);
        tvDownloadedNum = (TextView) findViewById(Rx.id.kg_tv_downloaded_num);
        tvDownloadSpeed = (TextView) findViewById(Rx.id.kg_tv_download_speed);
        tvDownloadPercent = (TextView) findViewById(Rx.id.kg_tv_download_percent);
        tvDownloadLeftTime = (TextView) findViewById(Rx.id.kg_tv_download_left_time);

        progressBar = (ProgressBar) findViewById(Rx.id.kg_progressbar);
        tvUpdateNow.setOnClickListener(this);

        tvUpdateContent.setText("" + checkUpdateInfo.getUpdateContent());
        tvAppName.setText("" + checkUpdateInfo.getBannerTitle());
    }

    private void initAppIcon() {
        String iconUrl = checkUpdateInfo.getBannerUrl();
        String imgKey = iconUrl + "-" + checkUpdateInfo.getVersionCode();
        String savePath = FolderManager.IMAGE_CACHE_FOLDER + AppUtil.getFileNameFromUrl(iconUrl);
        ivBanner.setTag(imgKey);
        Bitmap bitmap = mAsyncImageLoader.loadImage(this, imgKey, iconUrl, savePath, this);
        if (bitmap == null) {
            ivBanner.setImageResource(Rx.drawable.kg_force_update_banner_default);
        } else {
            ivBanner.setImageBitmap(bitmap);

            // 发送统计-强更广告图展示
            StaticsManager.sendCommonStatis(StatCmd.CMD_BI_FORCEUPDATE_BINNER_SHOW);
        }
        AppUtil.setFadeIn(this, ivBanner, 300);

    }

    private void initViewState() {
        String filehash = MD5Util.getMd5(checkUpdateInfo.getPackageAddress());
        DownloadFile file = DownloadOperator.getInstance().query(filehash);
        if (file != null) {
            String filePath = file.getFilePath();
            if (!FileUtil.isFileExist(filePath)) {
                // 删除该条应用的本地记录和缓存信息
                DownloadOperator.getInstance().delete(filehash);
                DownloadServiceUtil.removeDownloadFileFromCache(filehash);
            } else {
                if (!filePath.endsWith(FileDownloader.TEMP_FILE_EXT_NAME)) {
                    if (context.getPackageManager().getPackageArchiveInfo(filePath, 0) != null) {
                        layoutDownloading.setVisibility(View.GONE);
                        layoutUpdateContent.setVisibility(View.VISIBLE);
                        tvUpdateContent.setText("主人，你已下载安装包，安装游戏不消耗任何流量啊~~");
                        tvUpdateNow.setText("安装游戏");
                    }
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        DownloadServiceUtil.removeListener(mProgressListener);
    }

    private IProgressListener mProgressListener = new IProgressListener() {

        @Override
        public void onProgressChanged(DownloadFile file, int state) {
            if (!checkUpdateInfo.getPackageAddress().equals(file.getResUrl())) {
                return;
            }
            Message msg = mProgressHandler.obtainMessage();
            msg.what = MSG_PROGRESS_CHANGED;
            msg.obj = file;
            msg.arg1 = state;
            mProgressHandler.sendMessage(msg);
        }

        @Override
        public void onError(DownloadFile file, int errorType) {
            if (!checkUpdateInfo.getPackageAddress().equals(file.getResUrl())) {
                return;
            }
            Message msg = mProgressHandler.obtainMessage();
            msg.what = MSG_ERROR;
            msg.obj = file;
            msg.arg1 = errorType;
            mProgressHandler.sendMessage(msg);
        }

    };

    private static final int MSG_PROGRESS_CHANGED = 1;

    private static final int MSG_ERROR = 2;

    private Handler mProgressHandler = new Handler() {

        public void handleMessage(Message msg) {
            if (msg.obj == null || !(msg.obj instanceof DownloadFile)) {
                return;
            }
            DownloadFile file = (DownloadFile) msg.obj;
            switch (msg.what) {
                case MSG_PROGRESS_CHANGED:
                    int state = msg.arg1;
                    onProgressChanged(file, state);
                    break;
                case MSG_ERROR:
                    int errorType = msg.arg1;
                    onError(file, errorType);
                    break;
            }
        };
    };

    /**
     * 下载进度改变回调
     * 
     * @param file
     * @param state
     */
    private void onProgressChanged(DownloadFile file, int state) {
        try {
            LogUtil.d(TAG, "onProgressChanged()--->" + state);

            if (file != null) {

                if (state == FileDownloader.DOWNLOADING) {// 正在下载
                    layoutDownloading.setVisibility(View.VISIBLE);
                    layoutUpdateContent.setVisibility(View.GONE);
                    tvDownloadedNum.setText(AppUtil.getSize(file.getHaveRead()) + "/"
                            + AppUtil.getSize(file.getFileSize()));
                    if (!TextUtils.isEmpty(getDownloadLeftTime(file))) {
                        tvDownloadLeftTime.setText("-" + getDownloadLeftTime(file));
                    }
                    tvDownloadPercent.setText(DownloadHelper.getDownloadingProgress(file) + "%");
                    tvDownloadSpeed.setText(file.getStatis().getCurrentSpeed() + "KB/S");
                    progressBar.setProgress(DownloadHelper.getDownloadingProgress(file));
                } else if (DownloadServiceUtil.isInWaittingQueue(file.getKey())) {// 等待下载队列中

                } else if (state == FileDownloader.INTERUPT) {// 暂停

                } else if (state == FileDownloader.FINISH) {// 下载完成
                    layoutDownloading.setVisibility(View.GONE);
                    layoutUpdateContent.setVisibility(View.VISIBLE);
                    tvUpdateNow.setText("安装游戏");
                    tvUpdateContent.setText("主人，你已下载安装包，安装游戏不消耗任何流量啊~~");
                    AppUtil.installApp(this, file.getKey());
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getDownloadLeftTime(DownloadFile file) {
        // 速度，单位：kb/s
        int speed = file.getStatis().getCurrentSpeed();
        // 剩余大小，单位：kb
        long leftsize = (file.getFileSize() - file.getHaveRead()) / 1024;
        if (speed == 0) {
            return "";
        }
        // 剩余时间，单位：s
        long time = leftsize / speed;
        return AppUtil.formatLongToTimeStr(time * 1000);
    }

    /**
     * 下载出现异常回调
     * 
     * @param file
     * @param errorType
     */
    private void onError(DownloadFile file, int errorType) {
        LogUtil.d(TAG, "onError()--->" + errorType);
        if (file != null) {
            String filehash = file.getKey();
            layoutDownloading.setVisibility(View.GONE);
            layoutUpdateContent.setVisibility(View.VISIBLE);

        }
    }

    @Override
    public void onClick(View v) {
        if (v == tvUpdateNow) {
            if (checkUpdateInfo != null) {
                if (!"安装游戏".equals(tvUpdateNow.getText())) {
                    String resUrl = checkUpdateInfo.getPackageAddress();
                    String key = MD5Util.getMd5(resUrl);
                    AppInfo appInfo = new AppInfo();
                    appInfo.setFilehash(key);
                    appInfo.setFileSize(checkUpdateInfo.getFileSize());
                    appInfo.setDownloadUrl(checkUpdateInfo.getPackageAddress());
                    appInfo.setAppName(checkUpdateInfo.getAppName());
                    appInfo.setPackageName(checkUpdateInfo.getPackageName());
                    appInfo.setVersionCode(checkUpdateInfo.getVersionCode());

                    ParamsWrapper params = DownloadHelper.getParamsWrapperFromAppinfo(appInfo);
                    DownloadHelper.download(params, null);

                } else {
                    AppUtil.installApp(this, MD5Util.getMd5(checkUpdateInfo.getPackageAddress()));
                }
            }
        } else if (v == ivBanner) {
            String linkUrl = checkUpdateInfo.getLinkUrl();
            if (!TextUtils.isEmpty(linkUrl)) {
                String url = linkUrl + "&uuid=" + AppUtil.getKugouUUID(this) + "&uid="
                        + AppUtil.getKugouUUID(this);
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                // TODO 正式调试，要改成url
                Uri content_url = Uri.parse(url);
                // Uri content_url = Uri.parse(linkUrl);
                intent.setData(content_url);
                startActivity(intent);

                // 发送统计--点击强更广告图
                StaticsManager.sendCommonStatis(StatCmd.CMD_BI_FORCEUPDATE_BINNER_CLICK);
            }
        }
    }

    @Override
    public void imageLoaded(Bitmap bitmap, String key) {
        View view = this.getWindow().getDecorView().findViewWithTag(key);
        if (view != null) {
            if (view instanceof ImageView) {
                ImageView iv = (ImageView) view;
                if (bitmap != null) {
                    iv.setImageBitmap(bitmap);
                    AppUtil.setFadeIn(this, view, 300);

                    // 发送统计-强更广告图展示
                    StaticsManager.sendCommonStatis(StatCmd.CMD_BI_FORCEUPDATE_BINNER_SHOW);
                }
            }
        }
    }

    @Override
    public void onBackPressed() {

    }
}
